#!/usr/bin/env node

var natman = require('../lib/natman');

var flatiron = require('flatiron'),
    colors = require('colors'),
    revalidator = require('revalidator'),
    utile = require('utile'),
    app = flatiron.app;

app.use(flatiron.plugins.cli, {
  dir: __dirname,
  usage: [
    'nananananananana',
    ' __   __       ___    ___________  ___  ___       ___       __   __ ',
    '|  \\ |  |     /   \\  |           ||   \\/   |     /   \\     |  \\ |  |',
    '|   \\|  |    /  ^  \\  ---|  |---- |  \\  /  |    /  ^  \\    |   \\|  |',
    '|       |   /  /_\\  \\    |  |     |  |\\/|  |   /  /_\\  \\   |       |',
    '|  |\\   |  /  _____  \\   |  |     |  |  |  |  /  _____  \\  |  |\\   |',
    '|__| \\__| /__/     \\__\\  |__|     |__|  |__| /__/     \\__\\ |__| \\__|',
    '',
    '',
    'natman open <internal private port> <requested public port>',
    '',
    'options:',
    '',
    '     -g to specify gateway',
    '',
    'example:',
    '',
    '    natman open 22 8000',
    ''
  ]
});

app.config.use('file', { file: __dirname + '/../config/natman.json' });

var port = {
  type: "number",
  minimum: 1,
  maximum: 65535,
};

app.services = app.config.get('services');

//
// TODO: Clean up this block to one conditional instead of two
//

app.commands.open = function () {
  var args = utile.args(arguments);
  
  var nat = {
    private: null,
    public: null,
    gateway: null
  };
  
  if (args.length === 0) {
    app.log.warn('no port or service specified');
    return;
  }
  if(app.argv.g && app.argv.g.length > 0) {
    nat.gateway = app.argv.g.toString();
  }

  if (args.length === 1) {

    nat.private = args[0]

    if(typeof app.services[nat.private] !== 'undefined') {
      nat.private = app.services[nat.private]
    }

    nat.private = Number(nat.private);

    var validate = revalidator.validate({ port: nat.private }, { properties: { port: port }});
    
    if(!validate.valid){
      app.log.error('invalid service '.red + args[0].magenta);
      return;
    }
    return natman.createNat(nat);
  }

  if (args.length === 2) {

    nat.private = args[0]
    nat.public = args[1];

    if(typeof app.services[nat.private] !== 'undefined') {
      nat.private = app.services[nat.private]
    }

    if(typeof app.services[nat.public] !== 'undefined') {
      nat.public = app.services[nat.public]
    }

    nat.private = Number(nat.private);
    nat.public = Number(nat.public);

    var validate = revalidator.validate({ port: nat.private }, { properties: { port: port }});
    
    if(!validate.valid){
      app.log.error('invalid service '.red + args[0].magenta);
      return;
    }

    var validate = revalidator.validate({ port: nat.public }, { properties: { port: port }});

    if(!validate.valid){
      app.log.error('invalid service '.red + args[1].magenta);
      return;
    }

    return natman.createNat(nat);
  }
  
}

app.commands.help = function () {
  console.log('help', arguments)
}


app.start();



